package controllers

import (
	beego "github.com/beego/beego/v2/server/web"
	"main1/models"
)

type StoreController struct {
	beego.Controller
}
type JsonR struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

func (c *StoreController) Add() {
	name := c.GetString("name")
	types := c.GetString("types")
	img := c.GetString("img")
	dayMoney, _ := c.GetFloat("dayMoney")
	cateId, _ := c.GetInt("cateId")
	store := models.Store{

		Name:     name,
		Types:    types,
		Img:      img,
		DayMoney: dayMoney,
		CateId:   uint(cateId),
	}
	err := models.DB.Create(&store).Error
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 0,
			Msg:  "添加失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "添加成功",
			Data: nil,
		}
		c.ServeJSON()
	}
}
func (c *StoreController) Upload() {
	file, header, err := c.GetFile("img")

	defer file.Close()
	path := "static/img/" + header.Filename
	err = c.SaveToFile("img", path)
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 0,
			Msg:  "图片上传失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		imgSrc := "http://127.0.0.1:8080/" + path
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "图片上传成功",
			Data: imgSrc,
		}
		c.ServeJSON()
	}

}
func (c *StoreController) List() {
	page, _ := c.GetInt("page", 1)
	size, _ := c.GetInt("size", 4)

	pageData := make(map[string]interface{})

	query := models.DB.Model(&models.Store{})

	var count int64
	query.Count(&count)
	offset := (page - 1) * size

	var questions []models.Store
	err := query.Preload("StoreType").Offset(offset).Limit(size).Find(&questions).Error
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 0,
			Msg:  "查询失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		pageData["count"] = count
		pageData["questions"] = questions

		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "查询成功",
			Data: pageData,
		}
		c.ServeJSON()

	}

}
func (c *StoreController) Update() {
	id, _ := c.GetInt("id")
	name := c.GetString("name")
	types := c.GetString("types")
	img := c.GetString("img")
	dayMoney, _ := c.GetFloat("dayMoney")
	store := models.Store{
		Name:     name,
		Types:    types,
		Img:      img,
		DayMoney: dayMoney,
	}
	err := models.DB.Where("id=?", id).Updates(&store).Error
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 0,
			Msg:  "修改失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "修改成功",
			Data: nil,
		}
		c.ServeJSON()
	}
}
